package demo.algorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 *
 */
public class SpliteDemo {

    static Logger logger = LoggerFactory.getLogger(SpliteDemo.class);

    public static void main(String[] args) {
        SpliteDemo demo = new SpliteDemo();
        demo.testAssemble();
    }

    /**
     * 对list求和
     * 
     * @param list
     * @return
     */
    public static int sum(List<Integer> list) {
        if (list == null || list.isEmpty()) {
            return 0;
        }
        return list.stream().mapToInt(Integer::intValue).sum();
    }

    @Test
    public void testAssemble() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 5, 7, 8, 2);
        List<Integer> result = null;
        do {
            result = assemble(list, 10);
            logger.info("Result:{},List:{}", result, list);
        } while (result != null && !result.isEmpty());
    }

    /**
     * 从list里组合一组数据，该组的数据和小于等于sumLimit，并从list里删除相应的值
     * 
     * @param list
     * @param sumLimit
     * @return
     */
    public static List<Integer> assemble(List<Integer> list, int sumLimit) {
        List<Integer> result = new ArrayList<>();
        if (list == null || list.isEmpty()) {
            return result;
        }
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            Integer tmp = iterator.next();
            int tmpSum = sum(result) + tmp;
            if (tmp >= sumLimit || tmpSum > sumLimit) {
                continue;
            } else {
                result.add(tmp);
                iterator.remove();
            }
        }

        return result;
    }

    /**
     * 从list里组合一组数据，该组的数据和小于等于sumLimit，并从list里删除相应的值
     * 
     * @param list
     * @param sumLimit
     * @return
     */
    public static List<Integer> assemble(Collection<Integer> list, int sumLimit) {
        List<Integer> result = new ArrayList<>();
        if (list == null || list.isEmpty()) {
            return result;
        }
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            Integer tmp = iterator.next();
            int tmpSum = sum(result) + tmp;
            if (tmp >= sumLimit || tmpSum > sumLimit) {
                continue;
            } else {
                result.add(tmp);
                iterator.remove();
            }
        }

        return result;
    }
}
